package com.liveinstars.im.handler;

import com.liveinstars.im.common.enums.SpecialUserEnum;
import com.liveinstars.im.domain.dao.model.ChatGroup;
import com.liveinstars.im.domain.dao.model.Todo;
import com.liveinstars.im.domain.manager.ChatGroupManager;
import com.liveinstars.im.entity.ChatMessage;
import com.liveinstars.im.entity.Msg;
import com.liveinstars.im.core.Session;
import com.liveinstars.im.core.SessionManager;
import com.liveinstars.im.core.service.ChatGroupService;
import com.liveinstars.im.core.service.MessageService;
import com.liveinstars.im.core.service.TodoService;
import com.liveinstars.im.corebean.ClientLoginMessage;
import com.liveinstars.im.corebean.MsgHelper;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.UUID;


/**
 * 1、保持服务器间的心态 2、转发消息
 * 
 * @author ting
 *
 */
@Sharable
@Service
public class ClientLoginHandler extends
		SimpleChannelInboundHandler<ClientLoginMessage> {
	@Autowired
	private SessionManager sessionManager;

	@Autowired
	private TodoService todoService;

	@Autowired
	private ChatGroupService chatGroupService;

	@Autowired
	private MessageService messageService;

	@Autowired
	private ChatGroupManager chatGroupManager;

	public String imAssistantWelcome;

	@Override
	public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
		super.channelWritabilityChanged(ctx);
	}

	private static final Logger LOGGER = LoggerFactory.getLogger(ClientLoginHandler.class);

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, ClientLoginMessage message) throws Exception {
		try {
			Session session = sessionManager.clientLoginAuth(channelHandlerContext,
					message.getToken(), (long)message.getUserId(), message.getClientId(), message.getClientType());
			if (session != null) {
				Msg.Message m = MsgHelper.newResultMessage(
						Msg.MessageType.LOGIN_SUCCESS, "登录成功！");
				session.send(m);
				//第一次和小助手的会话
				try{
					ChatGroup chatGroup = chatGroupManager.getFriendsChatGroup((long) message.getUserId(), (long) SpecialUserEnum.IM_ASSISTANT.getId());
					//如果不存在，则说明需要第一次和小助手通信
					if (chatGroup == null || message.getUserId() == 331820) {
						if (message.getUserId() != 331820) {
							chatGroupService.addSpecialChatGroup((long) message.getUserId(), SpecialUserEnum.IM_ASSISTANT);
						}
						ChatMessage chatMessage = new ChatMessage();
						chatMessage.setId(messageService.getMsgId());
						chatMessage.setMsgType(ChatMessage.MSG_TYPE_UU);
						chatMessage.setUuid(UUID.randomUUID().toString());
						chatMessage.setUserName(SpecialUserEnum.IM_ASSISTANT.getName());
						chatMessage.setUserAvator(SpecialUserEnum.IM_ASSISTANT.getLogo());
						chatMessage.setUserGroupId(9);
						chatMessage.setFromId(SpecialUserEnum.IM_ASSISTANT.getId());
						chatMessage.setStatus(0);
						chatMessage.setToId(message.getUserId());
						chatMessage.setContent(imAssistantWelcome);
						chatMessage.setContentType(ChatMessage.CONTENT_TYPE_NORMAL);
						chatMessage.setType(ChatMessage.TYPE_SEND);
						chatMessage.setDate((int) LocalDateTime.now().atZone(ZoneId.systemDefault()).toEpochSecond());
						Msg.Message msg = MsgHelper.newChatMessage(chatMessage);
						session.send(msg);
					}
				} catch (Exception e) {
					LOGGER.error("发送小助手消息异常：{}",e.getMessage(),e);
				}
				// 发送代办消息
				List<Todo> todoList = todoService.listUnCompleteTodoByUserIdAndStartId((long) message.getUserId(), null);
				if (todoList != null && todoList.size() > 0) {
					Msg.Message m2 = MsgHelper.newTodoListMessage(todoList);
					session.send(m2);
				}
			} else {
				Msg.Message rtMessage = MsgHelper.newResultMessage(Msg.MessageType.LOGIN_ERROR, "用户认证失败!");
				LOGGER.info("用户登录失败。 msg:{}", message.toString());
				channelHandlerContext.channel().writeAndFlush(rtMessage);
				channelHandlerContext.channel().close();
			}
		} catch (Exception e) {
			Msg.Message rtMessage = MsgHelper.newResultMessage(Msg.MessageType.LOGIN_ERROR, "用户认证失败!");
			LOGGER.info("用户登录异常。 msg:{}", message.toString(), e);
			channelHandlerContext.channel().writeAndFlush(rtMessage);
			channelHandlerContext.channel().close();
		} finally {
			ReferenceCountUtil.release(message);
		}
	}
}